package com.leyou.sms.mq;

import com.leyou.common.mq.MQConstants;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class MessageListener {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private SmsProperties prop;

    /**
     * 监听 注册时短信验证码 类型短信
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.Queue.SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name = MQConstants.Exchange.SMS_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKey.VERIFY_CODE_KEY
    ))
    public void listenVerifyCodeMessage(Map<String,String> msg){
        // 获取电话号码
        String phones = msg.remove("phone");
        if(!RegexUtils.isPhone(phones)){
            // 电话为空
            log.error("发送短信的手机号为空或格式不正确");
            return;
        }
        // 获取验证码
        String code = msg.get("code");
        // 验证验证码是否符合阿里的规范
        if(!RegexUtils.isVerifyCode(code)){
            log.error("发送短信的验证码有误");
            return;
        }
        // 发送短信
        smsUtils.sendMessage(phones, prop.getSignName(), prop.getVerifyCodeTemplate(), JsonUtils.toString(msg));
    }
}
